<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DatabaseBackup
 *
 * @author kevinthant
 */
namespace Backuper\Services;
use Backuper\Settings\Database;
class DatabaseBackup {
    //put your code here
    private $_containerName = null;
    public function __construct(){
        $this->_containerName = Database::getInstance()->container;
    }
    
    public function backup(){
        
        $schemas = Database::getInstance()->schemas;
        
        foreach($schemas as $schema){
            $this->backupSchema($schema);
        }
    }
    
    public function backupSchema($schema){
        $clientPath = Database::getInstance()->clientPath;
        $username = Database::getInstance()->username;
        $password = Database::getInstance()->password;
        $filename = TEMP_DIR . DIRECTORY_SEPARATOR . $schema . '.sql';
        
        if(empty($password)){
            $cmd = sprintf('%s -u %s %s > %s', $clientPath, $username, $schema, $filename);
        }
        else{
            $cmd = sprintf('%s -u %s -p%s %s > %s', $clientPath, $username, $password, $schema, $filename);
        }
        
        echo "\n[DatabaseBackup] Executing Command : $cmd\n";
        $output = array();
        $return = 0;
        exec($cmd, $output, $return);
        
        if($return != 0){
            throw new \Exception('Fail to dump the database: '. $schema . implode("\n", $output));
        }
        
        if(!file_exists($filename)){
            throw new \Exception('Fail to dump the database: '. $schema);
        }
        
        CloudFiles::getInstance()->store(Database::getInstance()->container, $filename);
        
    }
}


